package com.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfiguration {
    @Bean("connectionFactory")//数据库0
    public LettuceConnectionFactory connectionFactory() {
        LettuceConnectionFactory connectionFactory;
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setDatabase(0);//连接数据
        redisConfig.setHostName("127.0.0.1");//Ip地址
        redisConfig.setPort(6379);//端口号
        LettucePoolingClientConfiguration poolingconfig = LettucePoolingClientConfiguration.builder().build();
        poolingconfig.getPoolConfig().setMinIdle(10);//设置最小空闲数
        poolingconfig.getPoolConfig().setMaxIdle(20);//设置最大空闲数
        poolingconfig.getPoolConfig().setMaxTotal(100);//设置连接最大总数
        connectionFactory = new LettuceConnectionFactory(redisConfig, poolingconfig);
        return connectionFactory;
    }

    //  @Bean("serviceConnectionFactory")//数据库1
    public LettuceConnectionFactory serviceConnectionFactory() {
        LettuceConnectionFactory connectionFactory;
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setDatabase(1);//连接数据
        redisConfig.setHostName("127.0.0.1");//Ip地址
        redisConfig.setPort(6379);//端口号
        LettucePoolingClientConfiguration poolingconfig = LettucePoolingClientConfiguration.builder().build();
        poolingconfig.getPoolConfig().setMinIdle(10);//设置最小空闲数
        poolingconfig.getPoolConfig().setMaxIdle(20);//设置最大空闲数
        poolingconfig.getPoolConfig().setMaxTotal(100);//设置连接最大总数
        connectionFactory = new LettuceConnectionFactory(redisConfig, poolingconfig);
        return connectionFactory;
    }

    @Bean
    public CacheManager redisCacheManager(LettuceConnectionFactory connectionFactory, @Value("${service.cache-ttl:-1}") int ttl) {
        //FastJson序列化器
        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
        //配置rediscCache
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        //使用FastJson作为序列化器
        cacheConfiguration = cacheConfiguration.serializeValuesWith(RedisSerializationContext
                .SerializationPair
                .fromSerializer(serializer))
                .entryTtl(Duration.ofMinutes(ttl));//指定缓存时间为10分钟
        //构建Redis
        RedisCacheManager redisCacheManager = RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory))
                .cacheDefaults(cacheConfiguration)//指定配置文件
                .build();//创建缓存管理器
        return redisCacheManager;


    }

    @Bean("jsonRedisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //使用fastjson序列化器
        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());//键的序列化器
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean()
    public StringRedisTemplate StringRedisTemplate(LettuceConnectionFactory connectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        stringRedisTemplate.setValueSerializer(new StringRedisSerializer());
        stringRedisTemplate.setKeySerializer(new StringRedisSerializer());//键的序列化器
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (int i = 0; i < params.length; i++) {
                if (params[i] != null) {
                    String s = params[i].toString();
                    sb.append(params[i].toString().trim());
                }
            }

            return sb.toString();
        };

    }
}
